Passed
Push — master ( 33081a...0dd98d )
by Paul
05:28
created

Tabs.onClick_   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 1
dl 0
loc 6
rs 9.4285
c 0
b 0
f 0
1
/** global: GLSR, jQuery */
2
;(function( x ) {
3
4
	'use strict';
5
6
	var Tabs = function( options ) {
7
		this.options = x.extend( {}, this.defaults, options );
8
		this.active = document.querySelector( 'input[name=_active_tab]' );
9
		this.referrer = document.querySelector( 'input[name=_wp_http_referer]' );
10
		this.tabs = document.querySelectorAll( this.options.tabSelector );
11
		this.views = document.querySelectorAll( this.options.viewSelector );
12
		if( !this.active || !this.referrer || !this.tabs || !this.views )return;
13
		this.init_();
14
	};
15
16
	Tabs.prototype = {
17
		defaults: {
18
			tabSelector: '.glsr-nav-tab',
19
			viewSelector: '.glsr-nav-view',
20
		},
21
22
		/** @return void */
23
		init_: function() {
24
			[].forEach.call( this.tabs, function( tab, index ) {
25
				var active = location.hash ? tab.getAttribute( 'href' ).slice(1) === location.hash.slice(2) : index === 0;
26
				if( active ) {
27
					this.setTab_( tab );
28
				}
29
				tab.addEventListener( 'click', this.onClick_.bind( this ));
30
				tab.addEventListener( 'touchend', this.onClick_.bind( this ));
31
			}.bind( this ));
32
		},
33
34
		/** @return string */
35
		getAction_: function( bool ) {
36
			return bool ? 'add' : 'remove';
37
		},
38
39
		/** @return void */
40
		onClick_: function( ev ) {
41
			ev.preventDefault();
42
			ev.target.blur();
43
			this.setTab_( ev.target );
44
			location.hash = '!' + ev.target.getAttribute( 'href' ).slice(1);
45
		},
46
47
		/** @return void */
48
		setReferrer_: function( index ) {
49
			var referrerUrl = this.referrer.value.split('#')[0] + '#!' + this.views[index].id;
50
			this.referrer.value = referrerUrl;
51
		},
52
53
		/** @return void */
54
		setTab_: function( el ) {
55
			[].forEach.call( this.tabs, function( tab, index ) {
56
				var action = this.getAction_( tab === el );
57
				if( action === 'add' ) {
58
					this.active.value = this.views[index].id;
59
					this.setReferrer_( index );
60
					this.setView_( index );
61
				}
62
				tab.classList[action]( 'nav-tab-active' );
63
			}.bind( this ));
64
		},
65
66
		/** @return void */
67
		setView_: function( idx ) {
68
			[].forEach.call( this.views, function( view, index ) {
69
				var action = this.getAction_( index !== idx );
70
				view.classList[action]( 'ui-tabs-hide' );
71
			}.bind( this ));
72
		},
73
	};
74
75
	GLSR.Tabs = Tabs;
76
})( jQuery );
77